

import * as defaultAddressQuery from './mall-address-queryDefault/Handler';
import * as addressInsert from './mall-address-insert/Handler';
import * as addressQuery from './mall-address-query/Handler';
import * as addressUpdate from './mall-address-update/Handler';
import { AuthWrapper } from './auth/AuthWrapper';
import * as Utils from './utils/Utils.js';

let myHandler = async function (event, context, callback, logger) {
  const credential = Utils.getCredential(context, logger);
  let operation;
  let params;
  let token;

  operation = event.body ? JSON.parse(event.body).operation : event.operation;
  params = event.body ? JSON.parse(event.body).params : event.params;
  token = event.body ? JSON.parse(event.body).token : event.token;

  logger.info("the operation is " + event.operation);

  try {
    // 创建AuthWrapper实例用于认证
    const authWrapper = new AuthWrapper(credential, logger);
    // 以下是被注释掉的认证和操作分发的代码块
    // 直接根据操作类型分发到对应的处理器
    // 如果是查询默认地址，调用defaultAddressQuery模块的myHandler函数
    // 如果是插入地址，调用addressInsert模块的myHandler函数
    // 如果是查询地址，调用addressQuery模块的myHandler函数
    // 如果是更新地址，调用addressUpdate模块的myHandler函数
    // 如果操作类型不匹配，返回错误信息
    const promise = authWrapper.verifyToken(token);
    promise
      .then((res) => {
        switch (operation) {
          case "defaultQuery":
            defaultAddressQuery.myHandler(params, context, callback, logger);
            break;
          case "insert":
            addressInsert.myHandler(params, context, callback, logger);
            break;
          case "query":
            addressQuery.myHandler(params, context, callback, logger);
            break;
          case "update":
            addressUpdate.myHandler(params, context, callback, logger);
            break;
          default:
            callback({
              ret: { code: -1, desc: "no such function" },
            });
        }
      })
      .catch((e) => {
        callback({
          ret: { code: -1, desc: "token verify failed" + e.getCode() },
        });
      });
    //     switch (operation) {
    //       case "defaultQuery":
    //         defaultAddressQuery.myHandler(params, context, callback, logger);
    //         break;
    //       case "insert":
    //         addressInsert.myHandler(params, context, callback, logger);
    //         break;
    //       case "query":
    //         addressQuery.myHandler(params, context, callback, logger);
    //         break;
    //       case "update":
    //         addressUpdate.myHandler(params, context, callback, logger);
    //         break;
    //       default:
    //         callback({
    //           ret: { code: -1, desc: "no such function" },
    //         });
    //     }
  } catch (e) {
    logger.error("token is " + e);
    callback({
      ret: { code: -1, desc: "token verify failed" },
    });
  }
};

module.exports.myHandler = myHandler;
